package com.jlastu.dlxy_androidapp.presenter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.util.Pair;

import androidx.annotation.NonNull;

import com.jlastu.dlxy_androidapp.base.WeakRefHandler;
import com.jlastu.dlxy_androidapp.contract.GoodsDetailsContract;
import com.jlastu.dlxy_androidapp.entity.Goods;
import com.jlastu.dlxy_androidapp.entity.Photo;
import com.jlastu.dlxy_androidapp.view.details.CommodityDetails;

import java.util.ArrayList;
import java.util.List;

public class GoodsDetailsPresenter implements GoodsDetailsContract.IGoodsDetailsPresenter {
    private static final int WHAT_GET_GOODS_LIST = 0;
    private GoodsDetailsContract.IGoodsDetailsView mGoodsDetailsView;
    private Context mContext;

    public GoodsDetailsPresenter(GoodsDetailsContract.IGoodsDetailsView goodsDetailsView, Context context) {
        mGoodsDetailsView = goodsDetailsView;
        mContext = context;
    }

    @Override
    public void getGoodsList(Integer GoodsID) {
        List<Goods> list = new ArrayList<>();

        List<Photo> list_P = new ArrayList<>();


        new Thread(new Runnable() {
            @SuppressLint("Range")
            @Override
            public void run() {
                //此处异步进行数据查询
//                Uri uri = Uri.parse("content://com.jlastu.znb.provider/goods/1");

                Log.d("TAG", "run: " + GoodsID);
                Uri uri = Uri.parse("content://com.jlastu.dlxy_androidapp.provider/goods/" + GoodsID);
                Cursor cursor = mContext.getContentResolver().query(
                        uri, null, null, null);
                Log.d("TAG", "cursor: " + cursor);
                Log.d("TAG", "cursor.moveToFirst(): " + cursor.moveToFirst());
                try {
                    if (cursor != null && cursor.moveToFirst()) {
                        do {
                            Goods goods = new Goods();
                            int goods_id = cursor.getInt(cursor.getColumnIndex("_id"));
                            goods.setId(goods_id);
                            goods.setStore_id(cursor.getInt(cursor.getColumnIndex("store_id")));
                            goods.setName(cursor.getString(cursor.getColumnIndex("goods_name")));
                            goods.setPrice(cursor.getDouble(cursor.getColumnIndex("goods_price")));
                            goods.setUnit(cursor.getString(cursor.getColumnIndex("goods_unit")));
                            goods.setClassify(cursor.getString(cursor.getColumnIndex("goods_classify")));
                            goods.setBrowseCount(cursor.getInt(cursor.getColumnIndex("goods_browse")));
                            goods.setMessage(cursor.getString(cursor.getColumnIndex("goods_message")));
                            list.add(goods);

                            Uri photoUri = Uri.parse("content://com.jlastu.dlxy_androidapp.provider/photo");
                            Cursor photoCursor = mContext.getContentResolver().query(
                                    photoUri,
                                    null,
                                    "goods_id = ?",
                                    new String[]{String.valueOf(goods_id)},
                                    null);
                            try {

                                if (photoCursor != null && photoCursor.moveToFirst()) {
                                    do {
                                        Photo photo = new Photo();
                                        photo.setId(photoCursor.getInt(photoCursor.getColumnIndex("_id"))); // 修正了这里的 cursor
                                        byte[] imageBlob = photoCursor.getBlob(photoCursor.getColumnIndex("image")); // 修正了这里的索引获取方式
                                        Bitmap bitmap = BitmapFactory.decodeByteArray(imageBlob, 0, imageBlob.length);
                                        photo.setData(imageBlob);
                                        photo.setBitmap(bitmap);
                                        Log.d("PhotoProvider", "photo_id = " + photo.getId());

                                        list_P.add(photo);

                                    } while (photoCursor.moveToNext());

                                }
                            } finally {
                                if (photoCursor != null) {
                                    photoCursor.close();

                                }
                            }
                        } while (cursor.moveToNext());
                    }
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }
//                Uri photoUri = Uri.parse("content://com.jlastu.dlxy_androidapp.provider/photo");
//                Cursor photoCursor = mContext.getContentResolver().query(
//                        photoUri, null, null, null);
//                try {
//
//                    if (photoCursor != null && photoCursor.moveToFirst()) {
//                        do {
//                            Photo photo = new Photo();
//                            photo.setId(photoCursor.getInt(photoCursor.getColumnIndex("_id"))); // 修正了这里的 cursor
//                            byte[] imageBlob = photoCursor.getBlob(photoCursor.getColumnIndex("image")); // 修正了这里的索引获取方式
//                            Bitmap bitmap = BitmapFactory.decodeByteArray(imageBlob,0, imageBlob.length);
//                            photo.setData(imageBlob);
//                            photo.setBitmap(bitmap);
//                            Log.d("PhotoProvider", "photo_id = " + photo.getId());
//
//                            list_P.add(photo);
//
//                        } while (photoCursor.moveToNext());
//
//                    }
//                } finally {
//                    if (photoCursor != null){
//                        photoCursor.close();
//
//                    }
//                }

                Pair<List<Goods>, List<Photo>> dataPair = new Pair<>(list, list_P);
                //子线程通过Handler发送消息，完成线程之间的通信。
                Message message = mHandler.obtainMessage(WHAT_GET_GOODS_LIST, dataPair);
                mHandler.sendMessage(message);
            }
        }).start();
    }

    Handler mHandler = new WeakRefHandler<>(Looper.getMainLooper(), this, new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            int what = msg.what;
            switch (what) {
                case WHAT_GET_GOODS_LIST:
                    Pair<List<Goods>, List<Photo>> dataPair = (Pair<List<Goods>, List<Photo>>) msg.obj;
                    // 获取两个列表
                    List<Goods> goodsList = dataPair.first;
                    List<Photo> photoList = dataPair.second;
                    mGoodsDetailsView.showGoodsList(goodsList, photoList);
                    break;
            }
            return false;
        }
    });
}
